package com.tingyuge.base.jdk.io.nio.buffer;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/11
 * @description
 */
public class BufferDemo2 {


    /**
     * 直接缓冲区
     */

    @Test
    public void buffer03() throws Exception {
        String inFile = "D:/nio/1.txt";
        FileInputStream fileInputStream = new FileInputStream(inFile);
        FileChannel channel = fileInputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream(new File("D:/nio/2.txt"));
        FileChannel outputChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while (true) {
            buffer.clear();

            int read = channel.read(buffer);
            if (read == -1) {
                break;
            }
            buffer.flip();
            outputChannel.write(buffer);
        }
    }

    /**
     * 只读缓冲区
     */

    @Test
    public void buffer02() {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);

        }
        //只读
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put(i, (byte) (i * 10));

        }
        readOnlyBuffer.position(0);
        readOnlyBuffer.limit(buffer.capacity());
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }
    }

    /**
     * 缓冲分片
     */
    @Test
    public void buffer01() {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);

        }
        //创建子缓冲区

        buffer.position(3);

        buffer.limit(7);

        ByteBuffer slice = buffer.slice();

        //改变子缓冲区

        for (int i = 0; i < slice.capacity(); i++) {
            byte b = slice.get();
            b *= 10;
            slice.put(i, b);

        }
        buffer.position(0);
        buffer.limit(buffer.capacity());
        while (buffer.remaining() > 0) {
            System.out.println(
                    buffer.get()
            );

        }
    }
}
